//
//  YSDecoder.m
//  YSEmoticonKeyboard
//
//  Created by MOLBASE on 2017/12/21.
//  Copyright © 2017年 YangShen. All rights reserved.
//

#import "YSDecoder.h"
#import "YYImage.h"
#import "NSAttributedString+YYText.h"

static CGSize                    _emotionSize;
static UIFont                    *_font;
static UIColor                   *_textColor;
static NSArray                   *_matches;
static NSString                  *_string;
static NSDictionary              *_emojiImages;
static NSMutableArray            *_imageDataArray;
static NSMutableAttributedString *_attString;
static NSMutableAttributedString *_resultString;

static NSString *const checkString = @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]";

@implementation YSDecoder

+ (NSMutableAttributedString *)decodeWithPlainString:(NSString *)plainString font:(UIFont *)font {
    if (!plainString) {
        return [[NSMutableAttributedString alloc]initWithString:@""];
    }
    
    _font = font;
    _string = plainString;
    _textColor = [UIColor blackColor];
    [self initProperty];
    [self executeMatch];
    [self setImageDataArray];
    [self setResultStrUseReplace];
    
    return _resultString;
}

+ (void)initProperty {
    // 读取并加载对照表
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Emotions" ofType:@"plist"];
    _emojiImages = [NSDictionary dictionaryWithContentsOfFile:path];
    
    // 文本间隔
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:4.0];
    
    NSDictionary *dict = @{NSFontAttributeName : _font, NSParagraphStyleAttributeName : paragraphStyle};
    CGSize maxSize = CGSizeMake(1000, MAXFLOAT);
    
    _emotionSize = [@"/" boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    
    _attString = [[NSMutableAttributedString alloc] initWithString:_string attributes:dict];
}

+ (void)executeMatch {
    //比对结果
    NSString *regexString = checkString;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString options:NSRegularExpressionCaseInsensitive error:nil];
    NSRange totalRange = NSMakeRange(0, [_string length]);
    
    _matches = [regex matchesInString:_string options:0 range:totalRange];
}

+ (void)setImageDataArray {
    NSMutableArray *imageDataArray = [NSMutableArray array];
    //遍历结果
    for (int i = (int)_matches.count - 1; i >= 0; i --) {
        NSMutableDictionary *record = [NSMutableDictionary dictionary];
        
        NSTextCheckingResult *match = [_matches objectAtIndex:i];
        
        NSRange matchRange = [match range];
        
        NSString *tagString = [_string substringWithRange:matchRange];
        
        NSString *imageName = [_emojiImages objectForKey:tagString];
        
        if (imageName == nil || imageName.length == 0) continue;
        
        [record setObject:[NSValue valueWithRange:matchRange] forKey:@"range"];
        
        [record setObject:imageName forKey:@"imageName"];
        
        [imageDataArray addObject:record];
    }
    _imageDataArray = imageDataArray;
}

+ (void)setResultStrUseReplace {
    NSMutableAttributedString *result = _attString;
    
    for (int i = 0; i < _imageDataArray.count ; i ++) {
        NSDictionary *imageDic = _imageDataArray[i];
        
        NSRange range = [imageDic[@"range"] rangeValue];
        NSString *imageName = imageDic[@"imageName"];
        
        NSString *path = [[NSBundle mainBundle] pathForResource:imageName ofType:@"gif"];
        NSData *data = [NSData dataWithContentsOfFile:path];
        
        // 缩小图片
        YYImage *image = [YYImage imageWithData:data scale:2];
        image.preloadAllAnimatedImageFrames = YES;
        
        YYAnimatedImageView *imageView = [[YYAnimatedImageView alloc] initWithImage:image];
        
        NSMutableAttributedString *attachText = [NSMutableAttributedString yy_attachmentStringWithContent:imageView contentMode:UIViewContentModeCenter attachmentSize:imageView.frame.size alignToFont:_font alignment:YYTextVerticalAlignmentCenter];
        
        [result replaceCharactersInRange:range withAttributedString:attachText];
    }
    
    _resultString = result;
}

@end
